<?php

namespace Project\Admin\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Hash;
use Project\Admin\Controllers\BaseController;

class AuthController extends BaseController
{

    /**
     * Get a JWT token via given credentials.
     *
     * @param  \Illuminate\Http\Request  $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        $credentials = request()->only($this->username, 'password');
        if ($this->auth->attempt($credentials)) {
            $user = $this->auth->user();
            if ($user->status !== 'normal') {
                return $this->fail('账号异常: 该账号已被禁用, 请联系管理员.');
            }
            $token = $this->guard()->fromUser($user, ['exp' => Carbon::now()->addMinutes($this->guard()->factory()->getTTL())->timestamp]);
            if ($token) {
                $user->sign_time = date('Y-m-d H:i:s');
                $user->sign_ip   = request()->ip();
                $user->sign_count++;
                $user->save();

                return $this->success(
                    [
                        'token' => [
                            'token_type'   => 'bearer',
                            'expires_in'   => $this->guard()->factory()->getTTL() * 60,
                            'access_token' => $token
                        ],
                        'user'  => $user
                    ],
                    '登录成功'
                );
            }
        }
        return $this->fail('账号或密码错误');
    }

    
    /**
     * Get the authenticated User
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        $data = $this->guard()->user();
        if($data){
            $data = $data->toArray();
            // 配合前端写的，到时完善的时候，可以去掉
            $data['roles'] = ['admin'];
        }
        return $this->success($data);
    }

    /**
     * Log the user out (Invalidate the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        $this->guard()->logout();
        return $this->success('退出成功');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken($this->guard()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => $this->guard()->factory()->getTTL() * 60
        ]);
    }

    public function menu(){
        $tree = [];
        $roles = \Project\Admin\Models\AdminUserRole::where('uid', $this->guard()->user()->id)->pluck('role_id')->toArray();
        if ($roles) {
            
            $role_names = \Project\Admin\Models\AdminRole::whereIn('id', $roles)->pluck('role_name')->toArray();
            $rules = \Project\Admin\Models\AdminRoleMenu::whereIn('role_name', $role_names)->pluck('rules')->toArray();
            $_mids = [];
            
            if ($rules) {
                foreach ($rules as $value) {
                    $_mids = array_merge($_mids, explode(',', $value));
                }
                $_mids = collect($_mids)->unique()->map(function ($item) {
                    return (int)$item;
                })->all();
                $menu = \Project\Admin\Models\AdminMenu::whereIn('id', $_mids)->orderBy('order', 'asc')->get();
                $tree = data_tree($menu->toArray());
            }
        }
        return $this->success($tree);
    }
}
